package cn.jiedh.app.meiweidk.welcome;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.MyTBView;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.event.Constant;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.BitmapUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LocationUtil;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ValidateUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.ImageCodeBean;
import cn.jiedh.app.meiweidk.entity.LoginAndRegisterBean;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jpush.android.api.JPushInterface;

/**
 * @name： 未开启一键登录 的注册页面
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/12/12
 * @modifyTime： 2017/12/12
 * @explain：
 */

public class LocalregistrationActivity extends BaseActivity {
    @BindView(R.id.tvmoney)
    TextView tvmoney;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.tvyongtu)
    TextView tvyongtu;
    @BindView(R.id.ll_yongtu)
    LinearLayout llYongtu;
    @BindView(R.id.tvphone)
    EditText tvphone;
    @BindView(R.id.etcode)
    EditText etcode;
    @BindView(R.id.verification_btn)
    MyTBView verificationBtn;
    @BindView(R.id.ll_phoneandcode)
    LinearLayout llPhoneandcode;
    @BindView(R.id.tvbtn)
    TextView tvbtn;
    OptionsPickerView MoneyPop;
    OptionsPickerView YongTuPop;
    @BindView(R.id.image_code_edt)
    EditText imageCodeEdt;
    @BindView(R.id.image_code_img)
    ImageView imageCodeImg;
    @BindView(R.id.image_code_layout)
    LinearLayout imageCodeLayout;

    private boolean bcode = false;
    private List<BuriedBean> buriedList;
    private List<MoneyBean> moneyBeanList = new ArrayList<>();
    private List<YongTuBean> yongTuBeanList = new ArrayList<>();
    private String img;
    private String imgKey;
    @Override
    protected int getLayoutView() {
        return R.layout.localregistration;
    }

    @Override
    protected void initView(View view) {
        tvbtn.setEnabled(false);
        initevent();
//        getImageCode();
        tvmoney.setText(SPUtils.getmoney()+"元");
    }


    private void getImageCode() {
        Map<String, Object> map = new HashMap<>();
        request(activity, UrlUtils.IMAGECODE, map, false, new ResponseSuccess<ImageCodeBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ImageCodeBean> response) {
                if (0 == response.getCode()) {
                    imageCodeLayout.setVisibility(View.GONE);

                } else if (1 == response.getCode()) {
                    T.showShort(response.getMessage());
                    imageCodeLayout.setVisibility(View.GONE);
                } else if (3 == response.getCode()) {
                    img = response.getData().getImg();
                    imgKey = response.getData().getImgKey();
                    Bitmap b = BitmapUtil.stringtoBitmap(img);
                    imgKey = response.getData().getImgKey();
                    imageCodeImg.setImageBitmap(b);
                    imageCodeLayout.setVisibility(View.VISIBLE);

                }
            }
        });
    }

    private void initevent() {
        tvmoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonChange();
            }
        });
        tvyongtu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonChange();
            }
        });
        etcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonChange();
            }
        });
        tvphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonChange();
            }
        });
        imageCodeEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonChange();
            }
        });
    }

    private void buttonChange() {
        String Smoney = tvmoney.getText().toString().trim();
        String Syongtu = tvyongtu.getText().toString().trim();
        String Sphone = tvphone.getText().toString().trim();
        String Scode = etcode.getText().toString().trim();
        String Simgcode = imageCodeEdt.getText().toString().trim();
        if (imageCodeLayout.isShown()){
            if (!TextUtils.isEmpty(Smoney) && !TextUtils.isEmpty(Syongtu) && !TextUtils.isEmpty(Sphone)
                    && !TextUtils.isEmpty(Scode)&&!TextUtils.isEmpty(Simgcode)) {
                tvbtn.setEnabled(true);
                tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_btn_red));
            } else {
                tvbtn.setEnabled(false);
                tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_gray1_bg));
            }
        }else{
            if (!TextUtils.isEmpty(Smoney) && !TextUtils.isEmpty(Syongtu) && !TextUtils.isEmpty(Sphone)
                    && !TextUtils.isEmpty(Scode)) {
                tvbtn.setEnabled(true);
                tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_btn_red));
            } else {
                tvbtn.setEnabled(false);
                tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_gray1_bg));
            }
        }
    }

    List<String> listmoney = new ArrayList<>();
    List<String> listyongtu = new ArrayList<>();

    @Override
    protected void initData() {
        if (SPUtils.getmoneylist().size() > 0 && SPUtils.getyongtulist().size() > 0) {
            for (int i = 0; i < SPUtils.getmoneylist().size(); i++) {
                if (i==SPUtils.getmoneylist().size()-1){
                    listmoney.add(SPUtils.getmoneylist().get(i).getName());
                }else{
                    listmoney.add(SPUtils.getmoneylist().get(i).getName() + "元");
                }
            }
            for (int i = 0; i < SPUtils.getyongtulist().size(); i++) {
                listyongtu.add(SPUtils.getyongtulist().get(i).getName());
            }
            initpop();
        }
    }

    private void initpop() {
        tvyongtu.setText(listyongtu.get(0));
        MoneyPop = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            tvmoney.setText(listmoney.get(options1));
            SPUtils.saveToApp(activity, ConfigUtils.MONEY, SPUtils.getmoneylist().get(options1).getValue()+"");
        }).setOutSideCancelable(false)
                .setDividerColor(R.color.hint3_text_color)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        YongTuPop = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            tvyongtu.setText(listyongtu.get(options1));
            SPUtils.saveToApp(activity, ConfigUtils.TYPE, SPUtils.getyongtulist().get(options1).getName()+"");
        }).setOutSideCancelable(false)
                .setDividerColor(R.color.hint3_text_color)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        MoneyPop.setPicker(listmoney);
        YongTuPop.setPicker(listyongtu);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_money, R.id.ll_yongtu, R.id.verification_btn, R.id.ll_phoneandcode, R.id.tvbtn,R.id.image_code_img})
    public void onViewClicked(View view) {
        String phone = tvphone.getText().toString().trim();
        String code = etcode.getText().toString().trim();
        String money = tvmoney.getText().toString().trim();
        String yongtu = tvyongtu.getText().toString().trim();
        switch (view.getId()) {
            case R.id.ll_money:
                if (MoneyPop != null) {
                    MoneyPop.show();
                }
                break;
            case R.id.ll_yongtu:
                if (YongTuPop != null) {
                    YongTuPop.show();
                }
                break;
            case R.id.verification_btn:
                MobclickAgent.onEvent(this,"newbie_getCode");
                if (isgetcode(phone)) {
                    getcode(phone);
                }
                break;
            case R.id.ll_phoneandcode:
                break;
            case R.id.tvbtn:
                SPUtils.saveBuried("click","0","引导页新用户专享-立即申请","true",
                        "引导页新用户专享",money,yongtu,"");
                if (imageCodeLayout.isShown()){
                    String imgcode = imageCodeEdt.getText().toString().trim();
                    if (ValidateUtils.isgotonext(money, yongtu, phone, code,imgcode)){
                        MobclickAgent.onEvent(activity,"newbie_apply");
                        login(phone, code);
                    }
                }else{
                    if (ValidateUtils.isgotonext(money, yongtu, phone, code)) {
                        MobclickAgent.onEvent(activity,"newbie_apply");
                        login(phone, code);
                    }
                }
                break;
            case R.id.image_code_img:
//                getImageCode();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    //验证码登录
    private void login(String phone, String code) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("authCodePage", code);
        map.put("unite", 0);
        Double[] doubles = LocationUtil.location;
        if (doubles != null) {
            Double lat = doubles[0];
            Double lng = doubles[1];
            String latStr = String.valueOf(lat);
            String lngStr = String.valueOf(lng);
            map.put("longitude", latStr);
            map.put("latitude", lngStr);
        }

        request(activity, UrlUtils.VERIFICATIONLOGIN, map, true, new ResponseSuccess<LoginAndRegisterBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoginAndRegisterBean> response) {
                dismissLoadingDialog();
                T.showShort(response.getMessage());
                if (0 == response.getCode()) {
                    SPUtils.saveToApp(activity,phone,SPUtils.getmoney());
                    SPUtils.saveUser(phone, response.getData().getToken());
                    JPushInterface.setAlias(activity, SPUtils.getPhone(), null);
                    ActivityUtil.next(activity, MainActivity.class);
                    EventScreen eventScreen=new EventScreen(Constant.NEWUSER,"");
                    EventUtils.getDefault().forward(eventScreen);
                    finish();
                }
                L.i("token：" + response.getData().getToken());
            }
        });
    }

    /**
     * 登录验证码
     *
     * @param phone
     */
    private void getcode(String phone) {
        verificationBtn.start();
        SPUtils.saveBuried("click","0","引导页新用户专享-获取验证码","true",
                "引导页新用户专享","","","");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("imgKey", imgKey);
        map.put("imgCode", imageCodeEdt.getText().toString());
        request(activity, UrlUtils.LOGINSMSCODE, map, true, new ResponseSuccess() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                if (response.getCode() == 0) {
                    bcode = true;
                } else {
                    verificationBtn.stop();
                }
                T.showShortToast(response.getMessage());
            }
        });
    }

    private boolean isgetcode(String phone) {
        if (TextUtils.isEmpty(phone)) {
            T.showShortToast("请输入手机号码");
            return false;
        }
//        if (!StringUtil.isMobileNO(phone)) {
//            T.showShortToast("请输入正确的手机号码");
//            return false;
//        }
        return true;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
